package class

import (

	
	"beego/testApp/common/tool"
	"time"
	"database/sql"
	"beego/testApp/common/db"
	_ "github.com/mattn/go-sqlite3"

)

type  Class struct {
    Cid        int
	Cname      string
	Tname      string
	Cnum       int
	Created    time.Time
	
   
}


func (c *Class) GetClassList(page int) []Class  {


	 var res []Class
      
	 db := db.Opendb("admin")
	 if(db==nil){
		 tool.Pic("class GetClassList","open or access db fail")
		 return nil
	 }

	 sql := "select * from class order by Created desc"

	 rows,err := db.Query(sql)

	 defer db.Close()

	 if(err!=nil){
		 tool.Pic("class GetClassList",err)
		 return nil
	 }

	 for rows.Next(){
		 var cid int
		 var cname string
		 var tname string
		 var cnum int
		 var created time.Time

		 rows.Scan(&cid,&cname,&tname,&cnum,&created)
	
		 classtemp := Class{Cid:cid,Cname:cname,Tname:tname,Cnum:cnum,Created:created}

         res =  append(res,classtemp)

	 }

	 defer rows.Close()


	 tool.Pic("class getclasslist",page)

	 return res;

}

func init(){
	
	db, err :=  sql.Open("sqlite3", "./db/admin.db")
	if(err!=nil){
		
		//fmt.Println("create or accesss admin db fail");
		tool.Pic("package class init ",err)
		

	}else{

		tool.Pic("package class init ","create or accesss admin db success")
		
	
	}
	
	sql_table := `CREATE TABLE IF NOT EXISTS class(
		Cid INTEGER PRIMARY KEY AUTOINCREMENT,
		Cname VARCHAR(32) NULL,
		Tname VARCHAR(32) NULL,
		Cnum INTEGER NULL,
		created DATE NULL
	);`

     db.Exec(sql_table)

     defer db.Close()
}



func (c *Class) AddClass() bool{

	db, err :=  sql.Open("sqlite3", "./db/admin.db")
	if(err!=nil){
		
		//fmt.Println("create or accesss admin db fail");
		tool.Pic("package class init ",err)
		return false

	}else{

		tool.Pic("package class init ","init success")

	}
	
	sql := "insert into class(Cname,Tname,Cnum,Created) values(?,?,?,?)"

	smt,err := db.Prepare(sql)

	defer db.Close()

	if(err!=nil){

		tool.Pic("AddClass",err)
		return false
	 }
	
	 now := time.Now(); 

	 res,err := smt.Exec(c.Cname,c.Tname,c.Cnum,now)

	 defer smt.Close()

	 if(err!=nil){
		tool.Pic("addclass exec fail",err)
		return false
	}

	affect, err := res.RowsAffected()

	//defer res.Close()

	if(err!=nil){
		tool.Pic("addclass affect fail",err)
		return false
	}

	tool.Pic("addclass success affected rows",affect)

     return true
}
